package com.snoweagler.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.snoweagler.VO.PageVO;
import com.snoweagler.mapper.RoleMapper;
import com.snoweagler.mapper.UserMapper;
import com.snoweagler.mapper.UserRoleMapper;
import com.snoweagler.params.UserParams;
import com.snoweagler.pojo.Role;
import com.snoweagler.pojo.User;
import com.snoweagler.pojo.UserExample;
import com.snoweagler.pojo.UserRole;
import com.snoweagler.service.UserService;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    UserRoleMapper userRoleMapper;
    @Override
    public PageVO<User> getUserList(UserParams params) {
        PageHelper.startPage(params.getCurrentPage(),params.getPageSize());
        List<User>  userList= userMapper.findByParams(params);
        PageInfo pi = new PageInfo(userList);
        PageVO<User> vo = new PageVO<>(pi.getTotal(),pi.getList());
        return vo;
    }

    @Override
    public void edit(User user) {
        if(user.getId() != null && !"".equals(user.getId())){
            user.setLastUpdateTime(new Date());

            userMapper.updateByPrimaryKeySelective(user);
        }else{
            user.setStatus((byte)1);
            user.setLastUpdateTime(new Date());
//            user.setSalt();
            userMapper.insert(user);
        }
    }

    @Override
    public List<Role> getOptions() {
        return roleMapper.selectByExample(null);
    }

    @Override
    public List<User> findAllUsers() {

        return userMapper.selectByExample(null);
    }

    @Override
    public User findOneByUserName(String username) {
        UserExample example = new UserExample();
        example.createCriteria().andNameEqualTo(username);
        List<User> userList = userMapper.selectByExample(example);
        return CollectionUtils.isEmpty(userList)?null:userList.get(0);
    }


}
